<template>
  <div class="login-container">
    <div class="login-form">
      <h2>学习管理系统登录</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名" 
            prefix-icon="User"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码" 
            prefix-icon="Lock"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleLogin" 
            :loading="loading"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <div class="register-link">
        还没有账号？<a href="#" @click="goToRegister">立即注册</a>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '../../utils/request'

// 定义登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 定义表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 定义响应式变量
const loading = ref(false)
const loginFormRef = ref()
const router = useRouter()

// 处理登录逻辑
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const response = await request.post('/api/auth/login', {
          username: loginForm.username,
          password: loginForm.password
        })
        
        if (response.data.token) {
          // 保存token到localStorage
          localStorage.setItem('token', response.data.token)
          localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo))
          
          // 获取用户权限
          try {
            const permissionResponse = await request.get(`/api/users/${response.data.userInfo.id}/permissions`)
            const permissions = permissionResponse.data.map((p: any) => p.permissionCode)
            
            // 更新localStorage中的用户信息，包含权限数据
            const userInfoWithPermissions = {
              ...response.data.userInfo,
              permissions: permissions
            }
            localStorage.setItem('userInfo', JSON.stringify(userInfoWithPermissions))
            
            // 发送storage事件通知其他监听器
            window.dispatchEvent(new StorageEvent('storage', {
              key: 'userInfo',
              newValue: JSON.stringify(userInfoWithPermissions)
            }))
          } catch (permissionError) {
            // 即使获取权限失败，也继续登录流程
            // 仍然更新localStorage，但不包含权限数据
            localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo))
            window.dispatchEvent(new StorageEvent('storage', {
              key: 'userInfo',
              newValue: JSON.stringify(response.data.userInfo)
            }))
          }
          
          // 跳转到首页
          router.push('/')
          
          ElMessage.success('登录成功')
        } else {
          ElMessage.error('登录失败')
        }
      } catch (error) {
        ElMessage.error('用户名或密码错误')
      } finally {
        loading.value = false
      }
    }
  })
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-form {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.login-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.register-link {
  margin-top: 20px;
  text-align: center;
}

.register-link a {
  color: #409eff;
  text-decoration: none;
}
</style>